package com.ecreditpal.audio.util;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.util.EntityUtils;

import java.util.concurrent.CountDownLatch;

/**
 * @author lifeng
 * @version 1.0 on 2017/10/20.
 * AsyncHttpClient 异步回调对象
 */
@Slf4j
@Getter
@Setter
public class HttpCallBack implements FutureCallback<HttpResponse> {
    private String key;
    private boolean stopped = false;
    private String content;
    private CountDownLatch countDownLatch;

    long startTime;

    public HttpCallBack(String key,CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
        this.key = key;

        startTime = System.currentTimeMillis();
    }

    @Override
    public void completed(HttpResponse response) {
        try {
//            long startToStringTime = System.currentTimeMillis();
            content = EntityUtils.toString(response.getEntity(), "UTF-8");
            countDownLatch.countDown();
//            long finishTime = System.currentTimeMillis();
//            log.info("success time cost: " + (finishTime - startTime));
//            log.info("convert to string time cost: " + (finishTime - startToStringTime));
        } catch (Exception e) {
            failed(e);
        }
    }

    @Override
    public void failed(Exception ex) {
        countDownLatch.countDown();
        stopped = true;
        log.error("can not get response",ex);

        long failedTime = System.currentTimeMillis();
        log.info("fail time cost: " + (failedTime - startTime));
    }

    @Override
    public void cancelled() {
        failed(new RuntimeException("task has been cancelled"));
    }




}
